<?php
/*
   +----------------------------------------------------------------------
   | WIKI 文档分发器
   +----------------------------------------------------------------------
   | Copyright (c) 2014 http://www.evildao.com All rights reserved.
   +----------------------------------------------------------------------
   | Author: 小子(LT) <mail@xiaoliu.org>
   +----------------------------------------------------------------------
   | Date:2016-11-12 16:52:52
   +----------------------------------------------------------------------
*/

$sync = [
	'wiki' => [
		'path' => '/usr/share/nginx/wiki-git/wiki',
		'password' => '',
		'repository' => 'https://username:password@git.oschina.net/ufox/wiki.git'
	],
];
try {
	$hook = $_POST['hook'];
	$hook = json_decode($hook, true);
} catch (Exception $e) {
	exit(-1);
}
$lock = 0;
if($hook['hook_name'] !== 'push_hooks') {
	exit(-2);
}

if(!isset($sync[$hook['push_data']['repository']['name']])) {
	exit(-3);
}

$sync = $sync[$hook['push_data']['repository']['name']];

if(!empty($sync['password']) && $hook['password'] !== $sync['password']) {
	exit(-4);
}

exec("./git_sync.sh \"{$sync['path']}\" \"{$sync['repository']}\"");

# 程序目录
define('APP_PATH', __DIR__.'/');
# 文本目录
define('MARK_PATH', $sync['path']. '/');
# 生成文件目录
define('SITE_PATH', '/usr/share/nginx/wiki/'. $hook['push_data']['repository']['name']. '/');
# 网站地址
define('WEB_SITE', 'http://wiki.evildao.com/');
# 是否有导航
$_GLOBAL['map'] = file_exists(MARK_PATH. 'this.map') ? null : false;

# 启动入口
loop_dir();
# 无限级文件挖掘
function loop_dir($path = '') {
	$ls = ls(MARK_PATH. $path);
	foreach ($ls as $v) {
		if(is_dir(MARK_PATH. $path.$v)) {
			loop_dir($path. $v.'/');
		}
		$_tt = explode('.', $v);
		if(end($_tt) == 'md') {
			$a = MARK_PATH. $path. $v;
			array_pop($_tt);
			array_push($_tt, 'html');
			$_tt = implode('.', $_tt);
			$b = SITE_PATH. $path. $_tt;
			mark_file($a, $b);
		}
	}
}
# 生成文件
function mark_file($a, $b) {
	require_once  APP_PATH. 'wiki/Parser.php';
	$parser = new \HyperDown\Parser();
	if(is_null($_GLOBAL['map'])) {
		$_GLOBAL['map'] = str_replace(['](','.md)'], [']('. WEB_SITE,'.html)'], file_get_contents(MARK_PATH. 'this.map'));
		$_GLOBAL['map'] = $parser->makeHtml($_GLOBAL['map']);
	}
	$markdown = $parser->makeHtml(file_get_contents($a));
	if($_GLOBAL['map'] !== false) {
		$tpl = 'book';
		$conf = [
			['{$title}', '{$nav}', '{$main}'],
			[basename($b), $_GLOBAL['map'], $markdown]
		];
	} else {
		$tpl = 'html';
		$conf = [
			['{$title}', '{$main}'],
			[basename($b), $markdown]
		];
	}
	$markdown = str_replace($conf[0], $conf[1], file_get_contents(APP_PATH. "wiki/{$tpl}.tpl"));
	$path = dirname($b);
	!is_dir($path) && mkdir($path, 0755, true);
	file_put_contents($b, $markdown);
}

//目录文件名获取函数
function ls($dir) {
	$handle = @opendir($dir);
	$list = array();
	while(true == ($file = readdir($handle))) {
		if ($file != "." && $file != "..") {
			$list[]=$file;
		}
	}
	closedir($handle); 
	return $list;
}